# -*- coding: utf-8 -*-
# @version : 1.0
# @File    : events.py
# @Date    : 2024/9/14 09:09
# @Author  : GlenZhao
# @Desc    : 全局事件
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

from application import settings
from utils.tools import import_modules_async
from apps.tasks import tasks

# 创建调度器实例（注意：BackgroundScheduler 是同步调度器）
scheduler = AsyncIOScheduler()

@asynccontextmanager
async def lifespan(app: FastAPI):

    await import_modules_async(settings.EVENTS, "全局模块", app=app, status=True)

    app.state.sse_clients = {}
    app.state.sse_lock = asyncio.Lock()

     #启动时添加任务
    scheduler.add_job(
        tasks.async_cron_job, 
        trigger=CronTrigger(second=0, minute="*/1"),  # 每分钟第0秒执行, 
        kwargs={"app": app},
        id="my_cron_job", 
        max_instances=1
    )
    scheduler.start()

    yield

    await import_modules_async(settings.EVENTS, "全局模块", app=app, status=False)
    app.state.sse_clients.clear()
    # 关闭时停止调度器
    scheduler.shutdown(wait=False)